package test.algorithmPlus;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * @Projectname: leetCode
 * @Filename: Lru
 * @Author: FANSEA
 * @Date:2024/9/5 9:23
 */
public class LruCache {

    public LruCache(int maxSize) {
        MAX_SIZE = maxSize;
    }

    public static class CacheObj {
        String key;
        String value;


        public CacheObj(String key, String value) {
            this.key = key;
            this.value = value;
        }
    }

    private final int MAX_SIZE;

    public final Map<String, CacheObj> cacheMap = new HashMap<>();
    public final LinkedList<CacheObj> cacheLinked = new LinkedList<>();

    public void put(String key, String value) {
        CacheObj cacheObj = new CacheObj(key, value);
        if (cacheMap.size()>=MAX_SIZE){
            cacheMap.remove(cacheLinked.getLast().key);
            cacheLinked.removeLast();
        }
        cacheMap.put(key, cacheObj);
        cacheLinked.addFirst(cacheObj);
    }

    public String get(String key) {
        if (! cacheMap.containsKey(key)) {
            return null;
        }
        CacheObj cacheObj = cacheMap.get(key);
        cacheLinked.remove(cacheObj);
        cacheLinked.addFirst(cacheObj);
        return cacheObj.value;
    }

    public static void main(String[] args) {
        LruCache lruCache = new LruCache(5);
        lruCache.put("1", "1");
        lruCache.put("2", "2");
        lruCache.put("3", "3");
        lruCache.put("4", "4");
        lruCache.put("5", "5");
        lruCache.put("6", "6");
        lruCache.put("1", "2");
        /*System.out.println(lruCache.get("1"));
        System.out.println(lruCache.get("2"));
        System.out.println(lruCache.get("3"));
        System.out.println(lruCache.get("4"));
        System.out.println(lruCache.get("5"));
        System.out.println(lruCache.get("6"));*/
        for (CacheObj cacheObj : lruCache.cacheLinked) {
            System.out.println(cacheObj.key + " : " + cacheObj.value);
        }
    }
}
